//
//  LabourItemViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 08/06/2017.
//  Copyright © 2017 Li Xiangyang. All rights reserved.
//

import UIKit

class LabourItemViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet var itemName: UITextField!
    @IBOutlet var quantity: UITextField!
    @IBOutlet var price: UITextField!
  
    var item : TwERPLabourItem!
    var gdVTC : DetailViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.preferredContentSize = CGSize(width: 350, height: 360)
        
    }
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        item?.description = itemName.text
        
        item?.quantity = NSInteger(quantity.text!)!
        item?.price = Float(price.text!)!
        gdVTC.serviceItems.reloadData()
        gdVTC.refreshServiceItems()
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return (gdVTC?.gongdanBeginEdit())!
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if textField == itemName {return true}
            
        let inverseSet = NSCharacterSet(charactersIn:"0123456789.").inverted
        
        // At every character in this "inverseSet" contained in the string,
        // split the string up into components which exclude the characters
        // in this inverse set
        let components = string.components(separatedBy: inverseSet)
        
        // Rejoin these components
        let filtered = components.joined(separator: "")  // use join("", components) if you are using Swift 1.2
        
        // If the original string is equal to the filtered string, i.e. if no
        // inverse characters were present to be eliminated, the input is valid
        // and the statement returns true; else it returns false
        return string == filtered
        
    }
    override func viewWillAppear(_ animated: Bool) {
        
        self.itemName.text = item.description
        self.quantity.text = String(format: "%d",(item.quantity))
        self.price.text = String(format: "%1.2f",(item.price))
        
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
